<template>
	<view class="container">
		<!-- <view class="status_bar"></view> -->
		<!--头部-->
		<!-- <view class="head flex-row" @tap="closeSwipe" :style="{'padding-right': posRight}">
			<view class="title">消息</view>
			<view @tap="toPage('/pages/message/group/create')">创建群聊</view>
		</view> -->
		<!--容器-->
		<scroll-view scroll-y class="list">
			<!-- <view class="space" @tap="closeSwipe"></view> -->
			<uni-swipe-action ref="swipe">
				<uni-swipe-action-item v-for="(item, index) in conversations" :key="index">
					<view class="item flex-row" @tap="toDetail(item)">
						<view class="cover flex-row flex-column">
							<!-- <image v-if="item.type == 'group' && item.groupFace" :src="item.groupFace" class="icon"></image>
							<image v-else-if="item.type == 'single' && item.userFace" :src="item.userFace" class="icon"></image>
							<image v-else src="../../static/img/face.png" class="icon"></image> -->
							<image :src="item.target.headerUrl" class="icon"></image>
							<view v-if="item.unReadNumebr" class="tag empty flex-row flex-column"></view>
					
						</view>
						<view class="title">
							<view class="main flex-row">
								<!--判断是群聊还是单聊-->
								<!-- <text v-if="item.type == 'group'" class="text">{{ item.groupName || '群聊'+item.groupId }}</text> -->
								<text class="text">{{ item.target.username }}</text>
								<!-- <text v-else class="text">{{ item.telephone }}</text> -->
								<!-- <text class="time">{{ item.conversation.content }}</text> -->
								<text class="time">{{formatDateTime(item.conversation.createTime)}}</text>
							</view>
							<!-- <view v-if="item.type == 'group'" class="sub text-ellipsis">{{ item.content }}</view> -->
							<!-- <view v-else class="sub text-ellipsis">{{ item.content }}</view> -->
							<view class="sub text-ellipsis">{{ item.conversation.content }}</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</scroll-view>
	</view>
</template>

<script>
	import uniIcons from '@/components/MassagePage/uni-icons/uni-icons.vue'
	import uniSwipeAction from '@/components/MassagePage/uni-swipe-action/uni-swipe-action.vue'
	import uniSwipeActionItem from '@/components/MassagePage/uni-swipe-action-item/uni-swipe-action-item.vue'
	export default {
		components: {
			uniIcons,
			uniSwipeAction,
			uniSwipeActionItem
		},
		data() {
			return {
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f9828a'
					}
				}],
				posRight: '15px',
				userId: uni.getStorageSync('userId') || '',
				list: [],
				conversations: [{
					conversation: {
						content: "测试",
						conversationId: "1112_2",
						createTime: "2023-10-23T06:07:25.000+0000",
						fromId: 2,
						id: 56,
						status: 0,
						toId: 1112,
					},
					letterCount: 1,
					target: {
						activationCode: "671f3fdb898e455997aec3d2bcb695a6",
						createTime: "2021-02-10T14:27:00.000+0000",
						email: "admin@banbang.com",
						headerUrl: "http://images.nowcoder.com/head/50t.png",
						id: 2,
						password: "",
						salt: "",
						status: 1,
						type: 1,
						username: "admin",
						wechatOpenId: null
					},
					unreadCount: 1
				}]
			}
		},
		onShow() {
			// 监听是否连接成功
			this.$xbcim.onsuccess(() => {
				console.log('连接成功')
			})

			// 监听连接是否错误
			this.$xbcim.onerror((error) => {
				console.log('error', error)
			})

			// 监听Sockect是否断开
			this.$xbcim.onclose(() => {
				console.log('连接断开')
			})

			// 接收消息
			this.$xbcim.onmessage(data => {
				this.list = this.list.map(item => {
					switch (item.type) {
						case 'group': // 群消息
							if (data.type == 'group' && item.groupId == data.target) {
								item.content = data.content
								item.date = '刚刚'
							}
							break
						case 'single': // 单聊消息
							if (data.type == 'single' && (item.fromUserId == data.source || item
									.toUserId == data.source)) {
								item.content = data.content
								item.date = '刚刚'
							}
							break
					}
					return item
				})
			})

			// this.getList()
			this.getList()

		},
		onLoad() {
			// #ifdef MP-WEIXIN
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.posRight = (menuButtonInfo.width + 20) + 'px'
			// #endif
			this.getList()
		},
		computed: {
	
		},
		methods: {
			// 关闭滑块
			closeSwipe() {
				this.$refs.swipe.closeOther()
			},
			// 详情
			toDetail(item) {
				uni.navigateTo({
					url: "/pages/sub/message/chat/chat?conversationId=" +item.conversation.conversationId 
				})
				
				// 判断是群聊还是单聊
				// if (item.type == 'group') {
				// 	uni.setStorageSync('groupName', item.groupName || '群聊' + item.groupId)
				// 	this.toPage('/pages/message/group/detail?groupId=' + item.groupId)
				// } else {
				// 	let {
				// 		fromUserId,
				// 		toUserId,
				// 		telephone
				// 	} = item
				// 	let userId = toUserId == this.userId ? fromUserId : toUserId
				// 	this.toPage('/pages/message/chat/index?toUserId=' + userId + '&toUserName=' + telephone)
				// }
			},
			// 切换
			swipeChange() {},
			// 处理消息类型
			// dealMessage(msg = '', type = 'text') {
			// 	let ret = msg;
			// 	switch (type) {
			// 		case 'voice':
			// 			ret = '语音消息';
			// 			break
			// 		case 'image':
			// 			ret = '图片';
			// 			break
			// 		case 'map':
			// 			ret = '位置信息';
			// 			break
			// 		default:
			// 			ret = msg
			// 	}
			// 	return ret
			// },
			// 获取用户消息
			getList() {
				self = this
				const url = "/api/letter/list?current=1&limit=10"
				this.$http({
					url: url,
					method: 'GET',
					data: {},
					header: {
						'ticket': uni.getStorageSync('ticket')
					}

				}).then(res => {
					self.conversations = res.data.data.conversations;
					console.log(res)
				})
			},
			
			// 关于时间
			formatDateTime(dateTimeStr) {
				const now = new Date(); // 当前时间
				const date = new Date(dateTimeStr);

				if (this.isSameDay(now, date)) {
					// 同一天，显示几点钟
					return `${this.getDayPeriod(date)} ${this.formatHourMinute(date)} `;
				} else if (this.isSameYear(now, date)) {
					// 今年到昨天，显示月日
					return this.formatDate(date, 'M月d日');
				} else {
					// 前一年，显示年月日
					return this.formatDate(date, 'yyyy年MM月dd日');
				}
			},
			

			// 判断两个日期是否为同一天
			isSameDay(date1, date2) {
				return (
					date1.getFullYear() === date2.getFullYear() &&
					date1.getMonth() === date2.getMonth() &&
					date1.getDate() === date2.getDate()
				);
			},
			// 判断日期2是否为日期1所在年份
			isSameYear(date1, date2) {
				return date1.getFullYear() === date2.getFullYear();
			},

			// 格式化时间为 'HH:mm'
			formatHourMinute(date) {
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				return `${hour}:${minute}`;
			},

			// 格式化日期为指定格式
			formatDate(date, format) {
				const map = {
					'M+': date.getMonth() + 1, // 月份
					'd+': date.getDate(), // 日
					'H+': date.getHours(), // 小时
					'm+': date.getMinutes(), // 分钟
					's+': date.getSeconds(), // 秒钟
					'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
					S: date.getMilliseconds() // 毫秒
				};

				if (/(y+)/.test(format)) {
					format = format.replace(
						RegExp.$1,
						(date.getFullYear() + '').substr(4 - RegExp.$1.length)
					);
				}

				for (let key in map) {
					if (new RegExp('(' + key + ')').test(format)) {
						format = format.replace(
							RegExp.$1,
							RegExp.$1.length === 1 ? map[key] : ('00' + map[key]).substr(('' + map[key]).length)
						);
					}
				}

				return format;
			},

			// 获取时间段（上午、下午、晚上）
			getDayPeriod(date) {
				const hour = date.getHours();
				if (hour < 6) {
					return '凌晨';
				} else if (hour < 12) {
					return '上午';
				} else if (hour < 18) {
					return '下午';
				} else {
					return '晚上';
				}

			}
		}
	};

</script>

<style lang="scss" scoped>
	.list {
		height: calc(100vh - 100upx - var(--status-bar-height));

		.item {
			width: 100vw;
			height: 160upx;
			padding: 30upx;
			box-sizing: border-box;
			align-items: flex-start;

			.cover {
				width: 100upx;
				height: 100upx;
				border-radius: 10upx;
				box-sizing: border-box;
				border: 2upx solid #f9f9f9;
				position: relative;

				.icon {
					width: 80upx;
					height: 80upx;
					// width: 100%;
					// height: 100%;
					border-radius: 10upx;
				}

				.tag {
					color: #fff;
					width: 30upx;
					height: 30upx;
					font-size: 20upx;
					border-radius: 50%;
					background-color: red;
					position: absolute;
					top: -12upx;
					right: -12upx;
					z-index: 9;

					&.empty {
						width: 20upx;
						height: 20upx;
						background-color: #F72727;
						top: -6upx;
						right: -6upx;
					}
				}
			}

			.title {
				height: 100%;
				box-sizing: border-box;
				width: calc(100vw - 130upx - 60upx);
				position: relative;

				&::after {
					content: '';
					width: 100%;
					height: 2upx;
					background-color: #F6F6F6;
					position: absolute;
					left: 0;
					bottom: -30upx;
				}

				.main {
					height: 40upx;
					margin: 6upx 0 12upx;

					.text {
						color: #333;
						font-size: 32upx;
						font-weight: 600;
					}

					.time {
						color: #666;
						font-size: 24upx;
					}
				}

				.sub {
					color: #999;
					font-size: 24upx;
				}
			}
		}
	}
	</style>